package cn.itcast.utils;

import android.os.Environment;
import android.util.Log;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import cn.itcast.AppConfig;
import cn.itcast.ApiRequest;

import cn.itcast.AuthConstants;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Http请求工具类
 * @author Zhangxiliang
 * @date 2021-11-20
 */

public class HttpUtil {

    /**
     * 接口名称：DownloadInterface
     * 接口作用：用于回调下载结果
     * 回调接口：onDownloadSuccess 下载成功
     * 回调接口：onDownloadFailure 下载失败
     * 回调接口：onProgressUpdate 下载进度
     * @author Zhangxiliang
     */
    public interface DownloadInterface {
        void  onDownloadSuccess();

        void onDownloadFailure();

        void onProgressUpdate(int progress);
    }


    /**
     * 方法名称：PostFile
     * 方法作用：上传文件
     * @param file 文件对象
     * @param fileInfo 文件信息对象
     * @param callback 回调
     * @author Zhangxiliang
     */
//    public static void PostFile(File file, FileInfo fileInfo, Callback callback) {
//        Map<String, String> mapParams = new HashMap<>();
//        //获取当前时间戳
//        Long timestamp = System.currentTimeMillis( );
//        mapParams.put (AuthConstants.APP_ID,String.valueOf(AppConfig.appId)) ;
//        mapParams.put (AuthConstants.APP_KEY, AppConfig.appKey ) ;
//        mapParams.put(AuthConstants.TIME_STAMP,String.valueOf(timestamp));
//        String token = "";
//            try {
//                token = MD5Util.encrypt(ApiRequest.buildApiRequest(mapParams).toString());
//            }catch(Exception e){}
//
//    RequestBody fileBody = RequestBody.create(MediaType.parse(FileUtil.getMimeType(file)), file);
//        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
//                .addFormDataPart("files", file.getName(), fileBody)
//                .addFormDataPart("username",fileInfo.getCreateBy())
//                .addFormDataPart("range",fileInfo.getFileRange().toString())
//                .addFormDataPart("appId" , String.valueOf(AppConfig.appId))
//                .addFormDataPart("timeStamp" ,String.valueOf(timestamp))
//                .addFormDataPart("token",token)
//                .build();
//        Request request = new Request.Builder().post(requestBody).url(AppConfig.host + "/file/api/upload").build();
//        OkHttpClient client = new OkHttpClient();
//        client.newCall(request).enqueue(callback);
//    }

    /**
     * 方法名称：downloadFile
     * 方法作用：文件下载
     * @param url 下载链接
     * @param downloadInterface 用于回调下载结果
     * @author Zhangxiliang
     */
//    public static void downloadFile(String url, final DownloadInterface downloadInterface) {
//        Map<String, String> mapParams = new HashMap<>();
//        //获取当前时间戳
//        Long timestamp = System.currentTimeMillis( );
//        mapParams.put (AuthConstants.APP_ID,String.valueOf(AppConfig.appId)) ;
//        mapParams.put (AuthConstants.APP_KEY, AppConfig.appKey ) ;
//        mapParams.put(AuthConstants.TIME_STAMP,String.valueOf(timestamp));
//        String token = "";
//        try {
//            token = MD5Util.encrypt(ApiRequest.buildApiRequest(mapParams).toString());
//        }catch(Exception e){}
//        if(url.contains("?"))
//            url = url+"&appId="+AppConfig.appId+"&timeStamp="+timestamp+"&token="+token;
//        else
//            url = url+"?appId="+AppConfig.appId+"&timeStamp="+timestamp+"&token="+token;
//
//
//        Request request = new Request.Builder().url(url).build();
//        OkHttpClient client = new OkHttpClient();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                downloadInterface.onDownloadFailure();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) {
//                //存储下载文件的目录
//                String savePath = "IMU_Study";
//                //从response获取文件名
//                String filename = response.header("Content-Disposition").split(";")[1].split("=")[1];
//                filename = URLDecoder.decode(filename);
//                //创建文件夹
//                FileUtil.createFolder(savePath);
//                //输入流
//                InputStream inputStream = null;
//                //输出流
//                FileOutputStream fileOutputStream = null;
//                //每次读取的字节大小（缓冲流）
//                byte readBytes[] = new byte[2048];
//                //读取的长度(写入的长度)
//                int length = 0;
//                try {
//                    //将服务器获取的文件传给输入流
//                    inputStream = response.body().byteStream();
//                    //获取文件总长度
//                    long sumLength = response.body().contentLength();
//                    //当前已下载长度
//                    long nowLength=0;
//                    //创建File对象 用于输出流创建文件
//                    File file = new File(Environment.getExternalStorageDirectory(), savePath+"/" + filename );
//                    //创建输出流
//                    fileOutputStream = new FileOutputStream(file);
//                    //循环将读到输入流的内容写入文件输出流
//                    while ((length=inputStream.read(readBytes))!=-1) {
//                        fileOutputStream.write(readBytes,0,length);
//                        //累计已下载长度
//                        nowLength+=length;
//                        //下载进度更新的回调接口
//                        downloadInterface.onProgressUpdate((int)(nowLength*1.0f/sumLength*100));
//                    }
//                    //把缓冲区的数据强行输出
//                    fileOutputStream.flush();
//                    //下载成功回调接口
//                    downloadInterface.onDownloadSuccess();
//                } catch (FileNotFoundException e) {
//                    //下载失败回调接口
//                    downloadInterface.onDownloadFailure();
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    //下载失败回调接口
//                    downloadInterface.onDownloadFailure();
//                    e.printStackTrace();
//                } finally {
//                    if (fileOutputStream != null) {
//                        try {
//                            fileOutputStream.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        });
//    }

    public static void getAllFile(String url, Callback callback) {

    }

    /**
     * 方法名称：getNameFromUrl
     * 方法作用：从下载链接解析出文件名
     * @param url 下载链接
     * @author Zhangxiliang
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }


    /**
     * GET请求接口
     * @param url
     * @param callback
     * @author Zhangxiliang
     */
    public static void get(String url,Callback callback){
        Map<String, String> mapParams = new HashMap<>();
        //获取当前时间戳
        Long timestamp = System.currentTimeMillis( );
        mapParams.put (AuthConstants.APP_ID,String.valueOf(AppConfig.appId)) ;
        mapParams.put (AuthConstants.APP_KEY, AppConfig.appKey ) ;
        mapParams.put(AuthConstants.TIME_STAMP,String.valueOf(timestamp));
        String token = "";
        try {
            token = MD5Util.encrypt(ApiRequest.buildApiRequest(mapParams).toString());
        }catch(Exception e){}
        if(url.contains("?"))
            url = url+"&appId="+AppConfig.appId+"&timeStamp="+timestamp+"&token="+token;
        else
            url = url+"?appId="+AppConfig.appId+"&timeStamp="+timestamp+"&token="+token;

        RequestBody body = RequestBody.create(MediaType.parse("application/json"),"");
        Request request = new Request.Builder()
                .url(url)
//                .addHeader("Authorization", "Bearer" + token)
                .get()
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(callback);
    }

    /**
     * POST请求接口
     * @param url
     * @param map
     * @param callback
     * @author Zhangxiliang
     */
    public static void post(String url,Map<String, String> map, Callback callback) {
        Map<String, String> mapParams = new HashMap<>();
        //获取当前时间戳
        Long timestamp = System.currentTimeMillis( );
        mapParams.put (AuthConstants.APP_ID,String.valueOf(AppConfig.appId)) ;
        mapParams.put (AuthConstants.APP_KEY, AppConfig.appKey ) ;
        mapParams.put(AuthConstants.TIME_STAMP,String.valueOf(timestamp));
        String token = "";
        try {
            token = MD5Util.encrypt(ApiRequest.buildApiRequest(mapParams).toString());
        }catch(Exception e){}
        if(url.contains("?"))
            url = url+"&appId="+AppConfig.appId+"&timeStamp="+timestamp+"&token="+token;
        else
            url = url+"?appId="+AppConfig.appId+"&timeStamp="+timestamp+"&token="+token;

        JSONObject jsonObject = new JSONObject(map);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        Log.d("code", ""+url);
        final Request request = new Request.Builder()
                .url(url)
//                .addHeader("Authorization", "Bearer" + token)
                .post(body)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(callback);
    }

}
